package com.andy.note.boot.config.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * AP World
 *
 * @auther: AndyChau
 * Date: 2021/8/24 9:36
 * Description:
 */
//@Component
//@Order(1)
//@WebFilter(filterName = "testFilter",urlPatterns = "/test/**")
public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Filter doFilter before chain");
        // 这里只拦截返回，直接让请求过去，如果在请求前有处理，可以在这里处理
        chain.doFilter( request,  response);
        ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse)response);//转换成代理类
        byte[] content = wrapperResponse.getContent();//获取返回值
        int status = wrapperResponse.getStatus();
        //判断是否有值
        if (content.length > 0)
        {

            String str = new String(content, "UTF-8");
            System.out.println("返回值:" + str);
            String ciphertext = null;

            try
            {
                //......根据需要处理返回值
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            //把返回值输出到客户端
            ServletOutputStream out = response.getOutputStream();
            out.write(ciphertext.getBytes());
            out.flush();
        }
        System.out.println("Filter doFilter after chain");
    }

    @Override
    public void destroy() {
        System.out.println("Filter destroy");
    }
}
